package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.dto.DishDto;
import com.itheima.dto.SetmealDto;
import com.itheima.entity.Category;
import com.itheima.entity.Dish;
import com.itheima.entity.Setmeal;
import com.itheima.entity.SetmealDish;
import com.itheima.service.CateGoryService;
import com.itheima.service.DishService;
import com.itheima.service.SetMealDishService;
import com.itheima.service.SetMealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.*;

import java.beans.Beans;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 套餐管理
 */
@RestController
@RequestMapping("/setmeal")
@Slf4j
public class SetMealController {
    @Autowired
    private SetMealDishService setMealDishService;
    @Autowired
    private SetMealService setMealService;
    @Autowired
    private CateGoryService cateGoryService;

    @Autowired
    private DishService dishService;

    /**
     * 新增套餐
     *
     * @param setmealDto
     * @return
     */
    @CacheEvict(value = "setmealCache",allEntries = true)//删除setmeal分类下面的所有的缓存
    @PostMapping
    public R<String> save(@RequestBody SetmealDto setmealDto) {
        log.info("新增菜品信息：{}", setmealDto);
        setMealService.saveWithDish(setmealDto);
        return R.success("新增套餐成功");
    }

    /**
     * 修改回显
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<Setmeal> get(@PathVariable Long id){
        Setmeal byId = setMealService.getByIdWithDishes(id);
        log.info("byid:{}",byId);
        return R.success(byId);
    }



     /**
     * 修改
     * @param setmealDto
     * @return
     */

    @CacheEvict(value = "setmealCache",allEntries = true)
    @PutMapping
    public R<String> put(@RequestBody SetmealDto setmealDto){
        log.info("setmealdto",setmealDto);
        setMealService.updateById(setmealDto);
        return R.success("修改成功");

}

    /**
     * 分页展示
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
        log.info("page:{},pageSize:{},name:{}", page, pageSize, name);
        Page<Setmeal> pageInfo = new Page<>(page, pageSize);
//        多封装一个套餐分类
        Page<SetmealDto> dtoPage = new Page<>(page, pageSize);

        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(name != null, Setmeal::getName, name);
        queryWrapper.orderByDesc(Setmeal::getUpdateTime);
        setMealService.page(pageInfo, queryWrapper);

//    查完后(pageInfo里面缺了一个套餐名称)，拷贝去dtoPage里面展示(拷贝分页）
        BeanUtils.copyProperties(pageInfo, dtoPage, "records");//不考records,自己添加
        List<Setmeal> records = pageInfo.getRecords();

        List<SetmealDto> list = records.stream().map((item) -> {//最后在赋给list
            SetmealDto setmealDto = new SetmealDto();
//       1. 先拷贝基本信息（拷贝信息）
            BeanUtils.copyProperties(item, setmealDto);
//        再去找category里面的套餐名称
            Long categoryId = item.getCategoryId();
            Category category = cateGoryService.getById(categoryId);

            if (category != null) {
//        从Category对象里面找出name
                String name1 = category.getName();
//         2.   在追加套餐名称
                setmealDto.setCategoryName(name1);
            }
            return setmealDto;

        }).collect(Collectors.toList());

//   3. 最后把list给dtoPage设置records(属性)
        dtoPage.setRecords(list);
        return R.success(dtoPage);

    }

    /**
     * 批量删除套餐，非基本数据类型，加注解
     * @param ids
     * @return
     */
    @CacheEvict(value = "setmealCache",allEntries = true)//删除setmeal分类下面的所有的缓存
    @DeleteMapping
    public R<String> delete(@RequestParam List<Long> ids) {
        log.info("ids:{}",ids);
        setMealService.removeWithDish(ids);
        return R.success("套餐删除成功");
    }

    /**
     * 更改售卖状态
     * @param status
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    @CacheEvict(value = "setmealCache",allEntries = true)
    public R<String> update(@PathVariable("status")int status, @RequestParam List<Long> ids){
        log.info("ids:{}",ids);
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(ids!=null,Setmeal::getId,ids);
        List<Setmeal> setmeals = setMealService.list(queryWrapper);
        for (Setmeal setmeal : setmeals) {
            if (setmeal !=null){
                //        更改状态
                setmeal.setStatus(status);
                setMealService.updateById(setmeal);
            }

        }
        return R.success("更改状态成功");

    }

    /**
     * 根据分类id查询套餐数据
     * @param setmeal
     * @return
     */
    @Cacheable(value = "setmealCache",key = "#setmeal.categoryId+'_'+#setmeal.status")
    @GetMapping("/list")
    public R<List<Setmeal>> list(Setmeal setmeal){
        log.info("参数：{}",setmeal.toString());
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(setmeal.getCategoryId() !=null,Setmeal::getCategoryId,setmeal.getCategoryId());
        queryWrapper.eq(setmeal.getStatus()!=null,Setmeal::getStatus,setmeal.getStatus());
        queryWrapper.orderByAsc(Setmeal::getUpdateTime);
        List<Setmeal> list = setMealService.list(queryWrapper);
        return R.success(list);

    }

    /**
     * 点击查看套餐中的菜品
     */
    @GetMapping("/dish/{id}")
    public R<List<DishDto>> dish(@PathVariable("id") Long SetmealId) {
        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SetmealDish::getSetmealId, SetmealId);
        //获取套餐里面的所有菜品  这个就是SetmealDish表里面的数据
        List<SetmealDish> list = setMealDishService.list(queryWrapper);

        List<DishDto> dishDtos = list.stream().map((setmealDish) -> {
            DishDto dishDto = new DishDto();
            //将套餐菜品关系表中的数据拷贝到dishDto中
            BeanUtils.copyProperties(setmealDish, dishDto);
            //这里是为了把套餐中的菜品的基本信息填充到dto中，比如菜品描述，菜品图片等菜品的基本信息
            Long dishId = setmealDish.getDishId();
            Dish dish = dishService.getById(dishId);
            //将菜品信息拷贝到dishDto中
            BeanUtils.copyProperties(dish, dishDto);

            return dishDto;
        }).collect(Collectors.toList());

        return R.success(dishDtos);
    }

}
